// 存储 Token
export const setTokens = (accessToken, refreshToken) => {
    wx.setStorageSync('accessToken', accessToken);
    wx.setStorageSync('refreshToken', refreshToken);
  };
  
  let isRefreshing = false; // 是否正在刷新 Token
  let requestsQueue = [];   // 等待中的请求队列
  
  // 基础请求方法（内部使用）
  const _request = (method, url, data) => {
    return new Promise((resolve, reject) => {
      const accessToken = wx.getStorageSync('accessToken');
      const headers = {
        'access-token': accessToken, // 默认只携带 access-token
      };
  
      wx.request({
        url,
        method,
        data,
        header: headers,
        success: async (res) => {
          if (res.statusCode === 401) { // Token 过期
            if (!isRefreshing) {
              isRefreshing = true;
              try {
                // 调用刷新接口（单独处理，携带 refresh-token）
                const refreshToken = wx.getStorageSync('refreshToken');
                const refreshRes = await _refreshToken(refreshToken);
                
                // 更新 Token 并重试原请求
                setTokens(refreshRes.accessToken, refreshRes.refreshToken);
                const retryRes = await _request(method, url, data);
                resolve(retryRes);
                
                // 重放队列中的请求
                requestsQueue.forEach(cb => cb());
                requestsQueue = [];
              } catch (err) {
                // 刷新失败，清空 Token 并跳转登录
                wx.removeStorageSync('accessToken');
                wx.removeStorageSync('refreshToken');
                wx.navigateTo({ url: '/pages/login/login' });
                reject(err);
              } finally {
                isRefreshing = false;
              }
            } else {
              // 正在刷新中，将请求加入队列
              requestsQueue.push(() => {
                _request(method, url, data).then(resolve).catch(reject);
              });
            }
          } else if (res.statusCode >= 200 && res.statusCode < 300) {
            resolve(res.data);
          } else {
            reject(res.data);
          }
        },
        fail: reject
      });
    });
  };
  
  // 刷新 Token 专用方法（携带 refresh-token）
  const _refreshToken = (refreshToken) => {
    return new Promise((resolve, reject) => {
      wx.request({
        url: '/member/getTokensByRefreshToken',
        method: 'POST',
        header: { 'refresh-token': refreshToken }, // 仅携带 refresh-token
        success: (res) => {
          if (res.data.success) {
            resolve(res.data.data); // 返回新 tokens
          } else {
            reject(new Error('刷新 Token 失败'));
          }
        },
        fail: reject
      });
    });
  };
  
  // 暴露快捷方法：request.get() / request.post()
  const request = {
    get: (url, data) => _request('GET', url, data),
    post: (url, data) => _request('POST', url, data),
    put: (url, data) => _request('PUT', url, data),
    delete: (url, data) => _request('DELETE', url, data)
  };
  
  export default request;